#include <stdio.h>
#include <string.h>
#include <mysql/mysql.h>

#define HOST "127.0.0.1"
#define PORT 3306
#define DATABASE "gobang"
#define USER "root"
#define PASSWORD "weiHE133035"

int main(){
    // 1.初始化mysql句柄
    MYSQL *mysql = mysql_init(NULL);
    if(mysql == NULL){
        printf("mysql init faild!\n");
        return -1;
    }
    // 2.连接数据库
    if(mysql_real_connect(mysql, HOST, USER, PASSWORD, DATABASE, PORT, NULL, 0) == NULL){
        printf("mysql connect faild!\n");
        mysql_close(mysql);
        return -1;
    }
    // 3.设置客户端字符集
    if(mysql_set_character_set(mysql, "utf8") != 0){
        printf("mysql set character faild!\n");
        mysql_close(mysql);
        return -1;
    }
    // 4.选择操作的数据库，没有就直接默认数据库
    // mysql_selectdb(MYSQL *mysql, const char *db)
    // 5.执行sql语句
    // const char *sql = "insert stu values(null, '未禾', 18, 60, 60, 60);";
    // const char *sql = "update stu set ch=ch+40 where id=1;";
    // const char *sql = "delete from stu where id=1;";
    char *sql = "select * from stu;";
    int ret = mysql_query(mysql, sql);
    if(ret != 0){
        printf("%s\t", sql);
        printf("mysql query faild! %s\n", mysql_error(mysql));
        mysql_close(mysql);
        return -1;
    }
    // 6.如果是查询语句 保存返回的结果集
    MYSQL_RES *res = mysql_store_result(mysql);
    if(res == NULL){
        printf("mysql store result faild!\n");
        mysql_close(mysql);
        return -1;
    }
    // 7.获取结果集行数
    int num_row = mysql_num_rows(res);
    // 8.获取结果集列数
    int num_col = mysql_num_fields(res);
    // 9.遍历结果集
    for(int i = 0; i < num_row; i++){
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < num_col; j++){
            printf("%s\t", row[j]);
        }
        printf("\n");
    }
    // 10.释放结果集
    mysql_free_result(res);
    // 11.关闭客户端连接
    mysql_close(mysql);
    return 0;
}